package com.liziyi0914.morearmor.effect;

import com.liziyi0914.morearmor.Utils;
import com.liziyi0914.morearmor.event.Listener;
import com.liziyi0914.morearmor.event.entity.EntityDamageByEntityEvent;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import net.minecraft.entity.ItemEntity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.loot.LootTables;
import net.minecraft.loot.context.LootContext;
import net.minecraft.loot.context.LootContextParameters;
import net.minecraft.loot.context.LootContextTypes;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.village.TradeOffer;
import net.minecraft.village.TradeOffers;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

/**
 * 2021/6/28<br>
 * MoreArmor<br>
 *
 * @author huanmeng_qwq
 */
public class EmeraldEffect extends AbstractEffect {
    @Listener
    public void onDamage(EntityDamageByEntityEvent e) {
        final LivingEntity entity = e.getEntity();
        if (!predicateArmor().test(entity)) {
            return;
        }
        List<ItemStack> items = new ArrayList<>();
        for (Int2ObjectMap<TradeOffers.Factory[]> map : TradeOffers.PROFESSION_TO_LEVELED_TRADE.values()) {
            for (TradeOffers.Factory[] value : map.values()) {
                for (TradeOffers.Factory factory : value) {
                    final TradeOffer tradeOffer = factory.create(e.getDamager(), random);
                    if (tradeOffer != null) {
                        items.add(tradeOffer.getSellItem());
                    }
                }
            }
        }
        final MinecraftServer server = entity.getEntityWorld().getServer();
        if (server != null && server.getLootManager() != null) {
            entity.getEntityWorld().getServer().getLootManager().getTable(LootTables.PIGLIN_BARTERING_GAMEPLAY)
                    .generateLoot(new LootContext.Builder((ServerWorld) entity.getEntityWorld())
                                    .parameter(LootContextParameters.THIS_ENTITY, entity).build(LootContextTypes.BARTER)
                            , items::add
                    );
        }
        if (items.isEmpty()) return;
        Collections.shuffle(items);
        if (entity.getEntityWorld() instanceof ServerWorld world) {
            world.spawnEntity(new ItemEntity(world, entity.getBlockX(), entity.getY(), entity.getZ(), Utils.randomGet(items)));
        }
    }

    @Override
    public Predicate<LivingEntity> predicateArmor() {
        return Utils.hasItemArmor(Items.EMERALD).or(Utils.hasItemArmor(Items.EMERALD_BLOCK));
    }
}
